package com.bort.system.filter;

import com.alibaba.fastjson.JSONObject;
import com.bort.system.utils.Result;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class AccessFilter extends FormAuthenticationFilter {
    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) {
        boolean allowed = super.isAccessAllowed(servletRequest, servletResponse, o);
        if(!allowed){
            String method = WebUtils.toHttp(servletRequest).getMethod();
            if(StringUtils.equalsAnyIgnoreCase("OPTIONS",method)){
                return true;
            }
        }
        return allowed;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        if(isLoginRequest(servletRequest,servletResponse)){
            if(isLoginSubmission(servletRequest,servletResponse)){
                return executeLogin(servletRequest,servletResponse);
            }else{
                return true;
            }
        }else{
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            response.setHeader("Access-Control-Allow-Origin",request.getHeader("Origin"));
            response.setHeader("Access-Control-Allow-Credentials","true");
            response.setContentType("application/json;charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            response.setStatus(200);
            PrintWriter writer = response.getWriter();
            Result res = Result.error("登录失效");
            res.setCode(201);
            writer.write(JSONObject.toJSONString(res));
            writer.flush();
            writer.close();
        }
        return false;
    }
}
